<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="归还时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker v-model="createTimeRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:admAssetReturn:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:admAssetReturn:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:admAssetReturn:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:admAssetReturn:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admAssetReturnList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="归还人" align="center" prop="returnId">
          <template #default="scope">
            <span>{{ scope.row.returnName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归还日期" align="center" prop="returnTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="projectId">
          <template #default="scope">
            <el-tooltip :content="scope.row.projectName" placement="top" :disabled="!scope.row.projectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.projectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="资产名称" align="center" prop="assetName">
          <template #default="scope">
            <el-tooltip :content="scope.row.assetName" placement="top" :disabled="!scope.row.assetName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.assetName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="编号" align="center" prop="number">
          <template #default="scope">
            <el-tooltip :content="scope.row.number" placement="top" :disabled="!scope.row.number">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.number }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="序列号" align="center" prop="serialNumber">
          <template #default="scope">
            <el-tooltip :content="scope.row.serialNumber" placement="top" :disabled="!scope.row.serialNumber">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.serialNumber }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:admAssetReturn:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:admAssetReturn:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改资产归还对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body class="seal-dialog">
      <template #default>
        <el-form ref="admAssetReturnFormRef" :model="form" :rules="rules" label-width="140px" label-position="left"
          style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="归还人" prop="returnId">
                <el-input v-model="form.returnName" placeholder="请输入借用人" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="部门" prop="deptId">
                <el-tree-select v-model="form.deptId" :data="deptTree" placeholder="请选择申请部门"
                  :props="{ label: 'label', value: 'id', children: 'children' }" check-strictly filterable
                  :default-expand-all="true" style="width: 100%" @visible-change="handleVisibleChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目名称" prop="projectName">
                <el-tree-select v-model="form.projectName" :data="projectTree" placeholder="请选择项目名称"
                  :props="{ label: 'contractName', value: 'id', children: 'children' }" filterable clearable
                  style="width: 100%" @change="handleProjectChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="归还日期" prop="returnTime">
                <el-date-picker clearable v-model="form.returnTime" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择归还日期" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资产名称" prop="assetName">
                <el-select v-model="form.assetName" placeholder="请选择资产" filterable clearable style="width: 100%"
                  @change="handleAssetChange">
                  <el-option v-for="item in assetOptions" :key="item.id" :label="item.assetName"
                    :value="item.assetName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入编号" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="form.brand" placeholder="请输入品牌" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="序列号" prop="serialNumber">
                <el-input v-model="form.serialNumber" placeholder="请输入序列号" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdmAssetReturn" lang="ts">
import { listAdmAssetReturn, getAdmAssetReturn, delAdmAssetReturn, addAdmAssetReturn, updateAdmAssetReturn } from '@/api/general/administration/asset/return';
import { AdmAssetReturnVO, AdmAssetReturnQuery, AdmAssetReturnForm } from '@/api/general/administration/asset/return/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { listProContract } from '@/api/project/init/contract';
import { pageListProInfo } from '@/api/project/init/proInfo';
import { ItemTreeNode } from '@/api/project/init/contract/types';
import { listAdmAssetStore } from '@/api/general/administration/asset/store';
import { AdmAssetStoreQuery } from '@/api/general/administration/asset/store/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admAssetReturnList = ref<AdmAssetReturnVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const admAssetReturnFormRef = ref<ElFormInstance>();

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 引入数据字典
const { adm_item_type, approval_record_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_record_status'));

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);
// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["综合整治院", "规划院", "工程中心"];
// 资产列表
const assetOptions = ref([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmAssetReturnForm = {
  id: undefined,
  returnId: userStore.userId,
  returnName: userStore.name,
  returnTime: formatLocalDate(),
  deptId: undefined,
  deptName: undefined,
  assetName: undefined,
  number: undefined,
  brand: undefined,
  serialNumber: undefined,
  remark: undefined,
  status: undefined,
  approverIdea: undefined,
}
const data = reactive<PageData<AdmAssetReturnForm, AdmAssetReturnQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    returnId: undefined,
    returnTime: undefined,
    deptId: undefined,
    assetName: undefined,
    number: undefined,
    brand: undefined,
    serialNumber: undefined,
    status: undefined,
    approverIdea: undefined,
    params: {
    }
  },
  rules: {
    serialNumber: [
      {
        required: true, message: "序列号不能为空", trigger: "blur"
      },
      {
        validator: (_rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("序列号不能输入中文"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    number: [
      {
        required: true, message: "编号不能为空", trigger: "blur"
      },
      {
        validator: (_rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("编号不能输入中文"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    returnId: [
      { required: true, message: "归还人不能为空", trigger: "blur" }
    ],
    returnTime: [
      { required: true, message: "归还日期不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门不能为空", trigger: "change" }
    ],
    projectName: [
      {
        validator: (rule, value, callback) => {
          // 当部门是指定部门时，项目名称必填
          const selectedDept = findDeptNode(deptTree.value, form.value.deptId);
          console.log(selectedDept);
          if (selectedDept && requiredProjectDepts.includes(selectedDept.label)) {
            if (!value) {
              return callback(new Error(selectedDept.label + "归还资产项目名称必填"));
            }
          }
          callback();
        },
        trigger: "change"
      }
    ],
    assetName: [
      { required: true, message: "资产名称不能为空", trigger: "blur" }
    ],
    brand: [
      { required: true, message: "品牌不能为空", trigger: "blur" }
    ]
  }
}
);

const { queryParams, form, rules } = toRefs(data);

// 递归查找部门节点
function findDeptNode(tree: any[], deptId: string | number): any {
  for (const node of tree) {
    if (node.id === deptId) return node;
    if (node.children && node.children.length > 0) {
      const found = findDeptNode(node.children, deptId);
      if (found) return found;
    }
  }
  return null;
}


/** 查询资产归还列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmAssetReturn(params);
    admAssetReturnList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  admAssetReturnFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmAssetReturnVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加资产归还";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmAssetReturnVO) => {
  if (row.status != 0) {
    ElMessage.error("只能对未审核的申请进行修改")
  } else {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getAdmAssetReturn(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改资产归还";
  }
}

/** 提交按钮 */
const submitForm = () => {
  admAssetReturnFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmAssetReturn(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addAdmAssetReturn(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmAssetReturnVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除资产归还编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmAssetReturn(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admAssetReturn/export', {
    ...queryParams.value
  }, `admAssetReturn_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
      tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取全部子项目（树级赋值，父节点不可选择）
const fetchProjectList = async () => {
  try {
    // 1. 获取合同列表
    const contractRes = await listProContract();
    const contracts = (contractRes?.rows || []).filter(
      (c: any) => c.contractStatus == 3
    );
    // 2. 获取项目列表
    const projectRes = await pageListProInfo();
    const projects = projectRes?.rows || [];
    // 3. 构建树结构
    const treeData = contracts.map((contract: any) => {
      const children = projects
        .filter((p: any) => p.contractId === contract.id)
        .map((p: any) => ({
          id: p.id,
          contractName: `${p.proName} (${p.proNumber})`, // 拼接 proName 和 proNumber
          contractId: contract.id
        }));

      return {
        id: contract.id,
        contractName: contract.contractName, // 父节点显示合同名
        disabled: true,
        children
      };
    });

    projectTree.value = treeData;
  } catch (error) {
    console.error("获取项目列表失败:", error);
    proxy?.$modal.msgError("获取项目列表失败");
  }
};

const fetchAssetOptions = async () => {
  try {
    const query: AdmAssetStoreQuery = {
      status: 1,    // 状态为 1
      isLend: 0,    // 未借出
      pageNum: 1,   // 必须提供
      pageSize: 1000 // 假设最大获取1000条，或者你可以根据实际情况调整
    };
    const res = await listAdmAssetStore(query); // 假设接口支持 params
    if (res.rows && Array.isArray(res.rows)) {
      assetOptions.value = res.rows.map((item: any) => ({
        id: item.id,
        assetName: item.assetName,
        brand: item.brand,
        serialNumber: item.serialNumber,
        number: item.number
      }));
    }
  } catch (error) {
    console.error("获取资产列表失败:", error);
    proxy?.$modal.msgError("获取资产列表失败");
  }
};

// 选择资产后同步字段
const handleAssetChange = (selectedName: string) => {
  const selectedAsset = assetOptions.value.find(item => item.assetName === selectedName);
  if (selectedAsset) {
    form.value.assetName = selectedAsset.assetName;
    form.value.brand = selectedAsset.brand;
    form.value.serialNumber = selectedAsset.serialNumber;
    form.value.number = selectedAsset.number;
    form.value.assetId = selectedAsset.id;
  } else {
    form.value.brand = '';
    form.value.serialNumber = '';
  }
};

const handleProjectChange = (selectedId: number) => {
  // 根据 selectedId 找到对应项目对象
  const findProject = (nodes: any[]): any => {
    for (const node of nodes) {
      if (node.id === selectedId) return node;
      if (node.children) {
        const child = findProject(node.children);
        if (child) return child;
      }
    }
    return null;
  };

  const project = findProject(projectTree.value);
  if (project) {
    form.value.projectId = project.id;
    form.value.projectName = project.contractName; // 或者 proName/proNumber 组合
  } else {
    form.value.projectId = null;
    form.value.projectName = '';
  }
};


onMounted(() => {
  getList();
  fetchDeptTree();
  fetchProjectList();
  fetchAssetOptions();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block;
  /* 确保是块级元素 */
}
</style>